package psn.zjk.performance;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.reflect.Method;
import java.security.ProtectionDomain;
import java.text.MessageFormat;

public class MyTransformer implements ClassFileTransformer {
    private Enhancer enhancer = new Enhancer();

    public MyTransformer() {
    }


    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        try {
            className = className.replace("/", ".");
            String packageName = getPackage(className);
            if (packageName.startsWith("com.erayt")) {
                System.out.println("==================111"+className);
                ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
                Class<?> clazz = systemClassLoader.loadClass(className);
                System.out.println("=========className==" + clazz);
                Object deserialize = SerializationUtils.deserialize(classfileBuffer);
                System.out.println("deserialize=================="+deserialize);
                Object o = Enhancer.create(clazz, new MethodInterceptor() {

                    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                        long start = System.currentTimeMillis();
                        Object result = method.invoke(o, objects);
                        System.out.println(MessageFormat.format("[{1}]耗时：{2}",
                                o.getClass().getName() + "#" + method.getName(), (System.currentTimeMillis() - start)));
                        return result;
                    }
                });
                System.out.println("zzzzzzzzzzzzzzzzz");
                clazz=null;
                systemClassLoader=null;
                System.gc();
                return SerializationUtils.serialize(o);
            }
        } catch (Exception e) {
        }
        return null;
    }

    private String getPackage(String className) {
        int i = className.lastIndexOf(".");
        return className.substring(0, i);
    }


}